# -*- coding: utf-8 -*-
"""
Copyright (c) 2012-2013, Andrew Berg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * The name of the author may not be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

# Convenience functions and classes for interfacing with the bot.
# Unlike the bot itself, this should be compatible with all Python versions 2.6 or higher.

import multiprocessing.connection
import json

class PermissionDenied(Exception):
	"""
	Used to abort the current command processing if the user is not allowed to use the command.
	"""
	pass

class InvalidArguments(Exception):
	pass

class JSONEncoderWithIter(json.JSONEncoder):
	def default(self, o):
		try:
			iterable = iter(o)
		except TypeError:
			pass
		else:
			return list(iterable)
		return json.JSONEncoder.default(self, o)
json_encoder = JSONEncoderWithIter(separators=(',', ':'))
json_decoder = json.JSONDecoder(strict=False)

class ConnectedServer(object):
	""" """
	def __init__(self, status_message):
		self.update(status_message)

	def __repr__(self):
		return '<ConnectedServer object for {}>'.format(self.config_network_name)

	def __eq__(self, other):
		return self.config_network_name == other.config_network_name

	def __hash__(self):
		return hash(self.network_name_config)
		
	def update(self, status_message):
		self.__dict__.update(status_message.__dict__)

class Channel(object):
	def __init__(self, info_dict):
		self.update(info_dict)

	def update(self, info_dict):
		self.__dict__.update(info_dict)

def establish_connection(address):
	global conn
	conn = multiprocessing.connection.Client(address)
	return conn

def send_message(conn, json_message):
	conn.send(json_message)

def ping_bot(conn):
	send_message(conn, json_encoder.encode({'action':'ping'}))

def pong_bot(conn):
	send_message(conn, json_encoder.encode({'action':'pong'}))

def send_die_message(conn, message):
	send_message(conn, json_encoder.encode({'action':'die', 'message':message}))

def register_module(conn, recv_events, recv_commands, recv_message_types=('privmsg',), commands=()):
	if not recv_commands:
		commands = ()
	message = {'action':'register', 'recv_events':recv_events, 'recv_commands':recv_commands, 'commands':commands, 'recv_message_types':recv_message_types}
	json_message = json_encoder.encode(message)
	send_message(conn, json_message)

def make_irc_message_json(message_type, args, message):
	message_dict = {'action':'irc_message', 'message_type':message_type, 'args':args, 'message':message}
	return json_encoder.encode(message_dict)